﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using UpperComputer.Application;
using UpperComputer.WPF.Entry.Common;
using UpperComputer.WPF.Entry.Common.Extensions;
using UpperComputer.WPF.Entry.Views;
using YFurion.Application;

namespace UpperComputer.WPF.Entry.ViewModels;

public class UserViewModel : ManagementViewModel
{
    private readonly IBaseUserService _userService;

    public BaseUserResultRequestDto Query { get; } = new BaseUserResultRequestDto();

    private PagedResultDto<BaseUserResultDto> _pagedResultDto = new();
    public PagedResultDto<BaseUserResultDto> PagedResultDto
    {
        get => _pagedResultDto;
        set => SetProperty(ref _pagedResultDto, value);
    }

    private BaseUserResultDto _currentBaseUser;
    public BaseUserResultDto CurrentBaseUser
    {
        get => _currentBaseUser;
        set => SetProperty(ref _currentBaseUser, value);
    }

    public UserViewModel(IBaseUserService userService)
    {
        _userService = userService;
    }

    protected override async Task LoadAsync(object parameter, CancellationToken cancellationToken)
    {
        SetCurrent(parameter);
        SetSkipCount(Query);
        PagedResultDto = await _userService.GetAll(Query, cancellationToken);
        CurrentBaseUser = null;
    }

    protected override async Task PostAsync(CancellationToken cancellationToken)
    {
        UserOperationControl menuButtonOperationControl = Furion.App.GetService<UserOperationControl>();
        object result = await ShowRootDialog(menuButtonOperationControl);
        if (result != null)
        {
            await LoadAsync(1, cancellationToken);
        }
    }

    protected override async Task PutAsync(CancellationToken cancellationToken)
    {
        if (CurrentBaseUser == null)
        {
            Snackbar.ShowWarningMessage("请选择一行编辑");
            return;
        }
        UserOperationControl menuButtonOperationControl = Native.CreateInstance<UserOperationControl>(CurrentBaseUser.Id);
        object result = await ShowRootDialog(menuButtonOperationControl);
        if (result != null)
        {
            await LoadAsync(null, cancellationToken);
        }
    }

    protected override async Task DeleteAsync(CancellationToken cancellationToken)
    {
        if (CurrentBaseUser == null)
        {
            Snackbar.ShowWarningMessage("请选择一行删除");
            return;
        }
        if (CurrentBaseUser.Account == Constant.ADMIN)
        {
            Snackbar.ShowWarningMessage("不能更改或删除超级管理员");
            return;
        }
        MessageBoxResult mbr = this.ShowQuestionBox("确定要删除吗");
        if (mbr == MessageBoxResult.OK)
        {
            await _userService.Delete(CurrentBaseUser.Id, cancellationToken);
            await LoadAsync(null, cancellationToken);
        }
    }
}
